#include "mouse_manip.h"

//-variaveis de pissa
Byte MSBy1 = 0;
Byte MSBy2 = 0;
Byte MSBy3 = 0;
int dx = 0;
int dy = 0;
int xov = 0;
int yov = 0;
int lmb = 0;
int mmb = 0;
int rmb = 0;

int cor_fundo = 15, cor_linha = 15, cor_rato = 15, cor_temp = 15;

void mouse_init()
{

	//Bool has_mouse = kbc_init(1);
	mask_pic(KBD_IRQ);
	mask_pic(MOUSE_IRQ);
	
	queueInit(&keys_queue);
	mouse_queue = newGQueue(10, sizeof(MouseData));
	
	install_asm_irq_handler(KBD_IRQ, kbd_isr, &old_kbd_irq);
	install_asm_irq_handler(MOUSE_IRQ, mouse_isr, &old_mouse_irq);
	
	unmask_pic(KBD_IRQ);
	unmask_pic(MOUSE_IRQ);
	
	x_pos = HRES / 2;
	y_pos = VRES / 2;
	
	set_pixel(x_pos, y_pos, 15, base);
	
	//return has_mouse;
}


void mouse_finalize()
{
	reinstall_asm_irq_handler(MOUSE_IRQ, &old_mouse_irq);
	reinstall_asm_irq_handler(KBD_IRQ, &old_kbd_irq);
	
	deleteGQueue(mouse_queue);
}


void parse_mouse_event()
{
	MouseData* package = (MouseData*)getGQueue(mouse_queue);
	MSBy1 = package->Byte1;
	MSBy2 = package->Byte2;
	MSBy3 = package->Byte3;
	dx = MSBy1 & XSGN ? (MSBy2 - 256) : MSBy2;
	dy = MSBy1 & YSGN ? (MSBy3 - 256) : MSBy3;
	xov = X_OVERFLOW(MSBy1);
	yov = Y_OVERFLOW(MSBy1);
	lmb = LEFT_BUTTON(MSBy1);
	mmb = MIDDLE_BUTTON(MSBy1);
	rmb = RIGHT_BUTTON(MSBy1);
}


void process_mouse_event_gfx()
{
	if(dx || dy)
	{
		int x_old = x_pos;
		int y_old = y_pos;
		
		//actualizar posicao do rato
		x_pos += dx;
		if(x_pos < 0) x_pos = 0;
		if(x_pos >= HRES) x_pos = HRES - 1;
		
		y_pos -= dy;
		if(y_pos < 0) y_pos = 0;
		if(y_pos >= VRES) y_pos = VRES - 1;
		
		//se o botao esquerdo estiver premido, desenhar pixel da linha
		//se o botao direito estiver premido, apagar pixel
		//senao, recolocar na posicao anterior o pixel temporario
		if(lmb || rmb)
			draw_line(x_old, y_old, x_pos, y_pos, (lmb ? cor_linha : cor_fundo), base);
		else
			set_pixel(x_old, y_old, cor_temp, base);
		
		//guardar cor do pixel por baixo do rato e mudar a cor para a cor do rato
		cor_temp = get_pixel(x_pos, y_pos, base);
		set_pixel(x_pos, y_pos, cor_rato, base);
	}
}
